package wechat.rcv.cosuming;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import wechat.rcv.data.JWTObject;
import wechat.rcv.util.ExecGet;
import wechat.rcv.util.ExecPost;
import windbell.domain.user.BaseUser;
import windbell.domain.user.WechatService;

@Component
public class AuthConsuming {
	
	final static Logger logger = Logger.getLogger(AuthConsuming.class.getName());
	
	private final static String APPID = "wx01ad0d700af56f26";
	
	private final static String SECRET = "87f6a972e47ee424d299970ce727ee60";
	
	private final static String WECHAT_URL_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	
	private JSONObject accessTokenObj = null;
//	
//	private static Date tokenTime = new Date();
//	
//	private static Long TOKEN_EXPIRATION_TIME = 7200*1000l; //7200S with a buffer
	
	private final static String WECHAT_DOMAIN_SERVER = "http://114.55.38.236:8099";
	
	@Autowired
	@Qualifier("windbell.domain.user.WechatService")
	private WechatService wechatService;
	
	public JSONObject getAccessToken(String code){
		
//		if (((new Date()).getTime()-tokenTime.getTime())>=TOKEN_EXPIRATION_TIME||accessTokenObj==null){
			String url = WECHAT_URL_ACCESS_TOKEN_URL + "?appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";
			try {
				accessTokenObj = new JSONObject(ExecGet.excuteGet(url));
				logger.info("json response=========================>" + accessTokenObj.toString());
//				tokenTime = new Date();
				return accessTokenObj;
			} catch (Exception e) {
				logger.info("get access token object exception: " + e.toString());
				e.printStackTrace();
			}
//		}
		
		return null;
	}
	
	public String getOpenId(String code) {
		try {
			return getAccessToken(code).getString("openid");
		} catch (JSONException e) {
			logger.info("get open id exception: " + e.toString());
			e.printStackTrace();
		} catch (Exception e) {
			logger.info("get open id other exception: " + e.toString());
			e.printStackTrace();
		}
		return null;
	}
	
	public String getAccessTokenStr(String code) {
		try {
			return getAccessToken(code).getString("access_token");
		} catch (JSONException e) {
			logger.info("get access token string exception: " + e.toString());
			e.printStackTrace();
		}
		return null;
	}
	
	public BaseUser getUserByCode(String code) {
		logger.info("===================>code: " + code);
		String openId = getOpenId(code);
		if (openId == null) return null;
		logger.info("getUserByCode:: open id is:" + openId);
		return wechatService.getUserbyWechatId(openId);
	}
	
	public JWTObject getJWT(String code) {
		
		BaseUser hUser = getUserByCode(code);
		
		if (hUser == null) return null;
		
//		userId = hUser.getId();
		
		String username = hUser.getUserid();
		String pwd = hUser.getPasswd();
		
		JSONObject param = new JSONObject();
		try {
			param.put("userid", username);
			param.put("passwd", pwd);
			logger.info("=================>param string: " + param.toString());
			String response = ExecPost.excuteJsonPost(WECHAT_DOMAIN_SERVER + "/login", param.toString());
			logger.info("==================?respose: " + response);
			JSONObject js = new JSONObject(response);
			return new JWTObject(js.getString("token"), hUser.getId());
		} catch (JSONException e) {
			logger.info("get access token JWT: " + e.toString());
			e.printStackTrace();
		}
		
		return null;
	}
	
	public String getRedirectUrl(String code, String state) {
		JWTObject jwt = getJWT(code);
		if (jwt == null) return null;
		return "http://wxh.puwu.biz/wechatlogin/" + jwt.getJwt() + ";state=" + state + ";id=" + jwt.getUserId();
	}
	
}
